ROMAIL_VERSION 		= "1.0"
ROMAIL_DELAY 		= 0.3
ROMAIL_MAX_ITEM 	= 10

local t, state, lastopened = 0.3, 0, 0
local ROMAIL_LANGUAGE = GetLanguage()

function RoMail_LoadFile(filename)
	local func, err = loadfile(filename)
	if err then	return false, err end
	dofile(filename)
	return true
end

if not RoMail_LoadFile("Interface/Addons/RoMail2/Locales/"..ROMAIL_LANGUAGE..".lua") then
	DEFAULT_CHAT_FRAME:AddMessage(string.format("Cannot load file: Interface/Addons/RoMail2/Locales/%s.lua", ROMAIL_LANGUAGE))
	RoMail_LoadFile("Interface/Addons/RoMail2/Locales/ENEU.lua")
end

function RoMail_OnLoad(this)
	this:RegisterEvent("VARIABLES_LOADED")
	
	this:RegisterEvent("MAIL_SHOW")
	this:RegisterEvent("MAIL_INBOX_UPDATE")
	this:RegisterEvent("MAIL_CLOSED")
	this:RegisterEvent("MAIL_SEND_INFO_UPDATE")
	this:RegisterEvent("MAIL_SEND_SUCCESS")
	this:RegisterEvent("MAIL_FAILED")
	this:RegisterEvent("CLOSE_INBOX_ITEM")
	this:RegisterEvent("CHAT_MSG_SYSTEM")
	this:RegisterEvent("CHAT_MSG_SYSTEM_GET")
	this:RegisterEvent("WARNING_MESSAGE")

	SaveVariables("RoMailSettings2")
	
	DefaultSettings = {
		["kMailFramePosition"] = { 5, 250 }
	}
	
	-- Fix: If Ui is reloaded while the Mail or Bank Frame was open it will cause a "still open" bug. So we close it.
	-- Disabled because of conflicts with zMailQueue
	--if not MailFrame:IsVisible() then CloseMail() end
	--if not BankFrame:IsVisible() then CloseBank() end
	
	RoMail_TakeAllRadioButton_OnClick(1)
	MoneyInputFrame_SetOnvalueChangedFunc(SendMailMoney, RoMailWire_onValueChangedFunc)
	
	if (type(RoMailSettings2) ~= "table") then
		RoMailSettings2 = DefaultSettings;
	else
		for k, v in pairs(DefaultSettings) do
			if (type(RoMailSettings2[k]) == "nil") then
				RoMailSettings2[k] = v;
			end
		end
	end
	
	DEFAULT_CHAT_FRAME:AddMessage(string.format(TEXT("ROMAIL_LOADED"), ROMAIL_VERSION, ROMAIL_LANGUAGE))
end

function RoMail_OnEvent(this, event)
	--DEFAULT_CHAT_FRAME:AddMessage("["..event.."] ("..arg1..") ("..arg2..") ("..arg3..") ("..arg4..") fired!") --DEBUG
	if ( event == "MAIL_SHOW" ) then
		this:Show()
	elseif ( event == "WARNING_MESSAGE" and TEXT("SYS_GAMEMSGEVENT_750") == arg1 ) then
		RoMail_StopOpening()
	elseif ( event == "CHAT_MSG_SYSTEM" and TEXT("SYS_NEW_MAIL") == arg1 ) then
		kMailFrame:Show()
		PlaySoundByPath("Interface/Addons/RoMail2/Sound/newmail.wav")
	else 
		kMailFrame:Hide()
	end
end

function RoMail_OnUpdate(this, elapsedTime)
	t = t + elapsedTime
	if not MailFrame:IsVisible()     		then RoMail_Close(this)   		end
	if     InboxFrame:IsVisible()    		then RoMail_CustomInbox() 		end
	if SendMailGroupDropDown:IsVisible() 	then RoMail_FriendButton:Hide(); RoMail_GuildButton:Hide(); end
	if SendMailNameEditBox:IsVisible() 		then RoMail_FriendButton:Show(); RoMail_GuildButton:Show(); end
	
	if state == 0 then 
		RoMailTakeAllButton:Enable()
		RoMailDeleteAllButton:Enable()
	else
		RoMailTakeAllButton:Disable()
		RoMailDeleteAllButton:Disable()
		RoMail_WaitForMail()
	end
end

function RoMail_GetAllAttachments()
	local NumItems = GetInboxNumItems()
	local itemsCount, moneyCount, moneyTotal = RoMail_HasAttachments(NumItems)
	
	if NumItems == 0 then DEFAULT_CHAT_FRAME:AddMessage(TEXT(ROMAIL_MAILBOX_EMPTY)) return end
	if RoMailTakeAllRadioButton:IsChecked()   and (itemsCount + moneyCount) <= 0 	then DEFAULT_CHAT_FRAME:AddMessage(TEXT(ROMAIL_NO_ATTAC_FOUND)) return end
	if RoMailTakeItemsRadioButton:IsChecked() and (itemsCount <= 0) 				then DEFAULT_CHAT_FRAME:AddMessage(TEXT(ROMAIL_NO_ITEMS_FOUND)) return end
	if RoMailTakeMoneyRadioButton:IsChecked() and (moneyCount <= 0) 				then DEFAULT_CHAT_FRAME:AddMessage(TEXT(ROMAIL_NO_MONEY_FOUND)) return end
	state = 1
	RoMail_OpenMail(NumItems)
end

function RoMail_HasAttachments(numItems)
	local moneyCount, itemsCount, moneyTotal = 0, 0, 0
	for i=1, numItems do
		local packageIcon, sender, subject, COD, moneyMode, money, daysLeft, paperStyle, items, wasRead, wasReturned, canReply = GetInboxHeaderInfo(i)
		if money and (money > 0) then 
			moneyCount = moneyCount + 1 
			moneyTotal = moneyTotal + money
		end
		if items and (items > 0) then itemsCount = itemsCount + 1 end
	end
	return itemsCount, moneyCount, moneyTotal
end

function RoMail_OpenMail(index)
	if not MailFrame:IsVisible() or index == 0 then return RoMail_StopOpening() end
	
	local packageIcon, sender, subject, COD, moneyMode, money, daysLeft, paperStyle, numItems, wasRead, wasReturned, canReply = GetInboxHeaderInfo(index)
	local pageIndex = INBOXITEMS_TO_DISPLAY
	
	while pageIndex <= index do pageIndex = pageIndex + INBOXITEMS_TO_DISPLAY end
	InboxFrame.pageNum = pageIndex / INBOXITEMS_TO_DISPLAY
	
	if ( COD ) then
		StaticPopup_Show("C.O.D. Mail(s) found. Please check them manually.")
	else
		TakeInboxItem(index)
		InboxFrame_Update()
	end
	
	local items = GetInboxNumItems()
		
	if (numItems and numItems > 1) or (items > 1 and index <= items) then
		lastopened = index
		t = 0
	else
		RoMail_StopOpening()
	end
end

function RoMail_WaitForMail()
	if state == 0 then return end
	if t > ROMAIL_DELAY then
		local packageIcon, sender, subject, COD, moneyMode, money, daysLeft, paperStyle, numItems, wasRead, wasReturned, canReply = GetInboxHeaderInfo(lastopened)
		if     RoMailTakeAllRadioButton:IsChecked()   and numItems  and money and (numItems + money) > 0 	then RoMail_OpenMail(lastopened)
		elseif RoMailTakeItemsRadioButton:IsChecked() and numItems 	and (numItems > 0) 						then RoMail_OpenMail(lastopened)
		elseif RoMailTakeMoneyRadioButton:IsChecked() and money 	and (money > 0)							then RoMail_OpenMail(lastopened)
		else
			if lastopened >= 1 then
				if money and (money <= 1) and (numItems <= 1) then
					lastopened = lastopened - 1
				else
					RoMail_OpenMail(lastopened - 1)
				end
			else
				RoMail_StopOpening()
			end
		end
	end
end

function InboxFrameItem_OnEnter(this)
	local packageIcon, sender, subject, COD, moneyMode, money, daysLeft, paperStyle, items, wasRead, wasReturned, canReply = GetInboxHeaderInfo(this.index)
	if items and (items > 0) then
		GameTooltip:SetOwner(this, "ANCHOR_RIGHT")
		GameTooltip:SetInboxItem(this.index)
		GameTooltip:Show()
	end
end

function RoMail_CustomInbox()
	local numItems 	= GetInboxNumItems()
	local index 	= ((InboxFrame.pageNum - 1) * INBOXITEMS_TO_DISPLAY) + 1
	local subjectText
	local itemsCount, moneyCount, moneyTotal = RoMail_HasAttachments(numItems)
	
	RoMailInboxCountMoneyText:SetText("|cffEAC000"..moneyTotal.."|r Gold total")
	RoMailInboxCountText:SetText("("..numItems..")")
	
	for i=1, INBOXITEMS_TO_DISPLAY do
		if ( index <= numItems ) then
			local packageIcon, sender, subject, COD, moneyMode, money, daysLeft, paperStyle, items, wasRead, wasReturned, canReply = GetInboxHeaderInfo(index)				
			
			if money and (money > 0) then
				subjectText = getglobal("MailItem"..i.."Subject")
				subjectText:SetText("|cffEAC000"..money.."|r Gold "..subject)
			end
		end
		index = index + 1
	end
end

function RoMail_DeleteRemains()
	local numItems 		= GetInboxNumItems()
	local remainsCount 	= 0	
	
	for i=1, numItems do
		local packageIcon, sender, subject, COD, moneyMode, money, daysLeft, paperStyle, items, wasRead, wasReturned, canReply = GetInboxHeaderInfo(i)
		if ( InboxItemCanDelete(i) and money == 0 and items == 0 ) then
			DeleteInboxItem(i)
			remainsCount = remainsCount + 1
		end
	end
	return remainsCount
end

function RoMail_DeleteAll()	
	local numItems 		= GetInboxNumItems()
	local remainsCount 	= RoMail_DeleteRemains()
	
	if remainsCount > 0 then
		for i=0, remainsCount do RoMail_DeleteAll() end
	end
	InboxFrame.pageNum = 1
	InboxFrame_Update()
end

function RoMail_TakeAllRadioButton_OnClick(index)
	if index == 1 then
		RoMailTakeAllRadioButton:SetChecked(1)
		RoMailTakeMoneyRadioButton:SetChecked(nil)
		RoMailTakeItemsRadioButton:SetChecked(nil)
	elseif index == 2 then
		RoMailTakeAllRadioButton:SetChecked(nil)
		RoMailTakeMoneyRadioButton:SetChecked(1)
		RoMailTakeItemsRadioButton:SetChecked(nil)
	elseif index == 3 then
		RoMailTakeAllRadioButton:SetChecked(nil)
		RoMailTakeMoneyRadioButton:SetChecked(nil)
		RoMailTakeItemsRadioButton:SetChecked(1)
	end
end

function RoMail_StopOpening()
	state = 0
end

function RoMail_Close(this)
	RoMail_StopOpening()
	this:Hide()
end

---------------------------------------------------------------------------------------------------------------------------------
-- RoMailWire: Update Subject Field with Money Amount if blank
---------------------------------------------------------------------------------------------------------------------------------
function RoMailWire_onValueChangedFunc()
	local itemName, itemTexture, stackCount = GetSendMailItem()
	local copper = MoneyInputFrame_GetCopper(SendMailMoney)
	local newSubjectText
	
	if copper and (copper > 0) then newSubjectText = "("..copper..") Gold" end
	
	if itemName then
		newSubjectText = itemName
		if stackCount > 0 then newSubjectText = itemName.."("..stackCount..")" 							end
		if copper > 0     then newSubjectText = "("..copper.." Gold), "..itemName.."("..stackCount..")" end
	end
	SendMailSubjectEditBox:SetText(newSubjectText)
end

---------------------------------------------------------------------------------------------------------------------------------
-- RoMail kMail: Mailbox Notification
---------------------------------------------------------------------------------------------------------------------------------
function RoMail_kMailFrame_Scripts_OnLoad(this)
	local scale, x, y = GetUIScale(), unpack(RoMailSettings2["kMailFramePosition"])
	this:Hide()
	this:ClearAllAnchors()
	this:SetAnchor("TOPLEFT", "TOPLEFT", "UIParent", x / scale, y / scale)
	this:RegisterEvent("VARIABLES_LOADED");
	this:RegisterEvent("MAIL_INBOX_UPDATE");
	kMailPost:SetText(ROMAIL_KMAIL_NEW);
end

function RoMail_kMailFrame_Scripts_OnEvent(this)
	if (event == "VARIABLES_LOADED") then
		RoMail_kMailFrame_Scripts_OnLoad(this);
	end;
end

function RoMail_kMailFrame_Scripts_OnEnter(this)
	GameTooltip:ClearAllAnchors();
	GameTooltip:SetAnchor("TOPLEFT", "TOPLEFT", "kMailFrame", 0, 0);
	GameTooltip:SetText(ROMAIL_KMAIL_TOOLTIP_T);
	GameTooltip:AddLine(ROMAIL_KMAIL_TOOLTIP);
end

function RoMail_kMailFrame_Scripts_OnLeave(this)
	GameTooltip:Hide();
end

function RoMail_kMailFrame_Scripts_OnMouseDown(this)
	this:StartMoving("TOPLEFT")
end

function RoMail_kMailFrame_Scripts_OnMouseUp(this)
	RoMail_kMailFrame_SavePosition(this);
	this:Hide();
	DEFAULT_CHAT_FRAME:AddMessage(ROMAIL_KMAIL_READ, 0.8, 0.5, 0.3);
end


function RoMail_kMailFrame_SavePosition(this)
	this:StopMovingOrSizing();
	RoMailSettings2["kMailFramePosition"] = { this:GetPos() }
end

---------------------------------------------------------------------------------------------------------------------------------
-- Freundeliste
---------------------------------------------------------------------------------------------------------------------------------
--[[ RoMailContacts: Contact List ]]--
function RoMail_MailGroupDropDown_OnLoad(this)
end
function RoMail_FriendList_OnEvent(this, event)
end

function RoMail_MailGroupDropDown_OnClink(this, name)
	RoMail_MailListFrame:Hide()
	local text = name
	local form = getglobal("RoMail_Form")
	form:SetText(text)
	form:Show()
	RoMail_MailListFrame:Show()
end

function RoMail_MailGroupTT_OnEnter(this, button)
	if (button=="guild") then
		GameTooltip:ClearAllAnchors();
		GameTooltip:SetAnchor("TOPLEFT", "TOPLEFT", "RoMail_GuildButton", 25, 0);
		GameTooltip:SetText(ROMAIL_TITLE_GUILD);
	elseif (button=="friend") then
		GameTooltip:ClearAllAnchors();
		GameTooltip:SetAnchor("TOPLEFT", "TOPLEFT", "RoMail_FriendButton", 25, 0);
		GameTooltip:SetText(ROMAIL_TITLE_FRIEND);
	end
end

function RoMail_MailGroupTT_OnLeave(this)
	GameTooltip:Hide();
end
	
function RoMail_FriendList_OnLoad(this)
	RoMail_MailListFrame.pern = 1
	RoMail_MailListFrame.index = 0
	RoMail_MailListFrame_ScrollBar:SetMinValue(0)
end

function RoMail_FriendList_OnShow(this)
	RoMail_FriendList_Update()
end

function RoMail_FriendList_Update()
	local form = getglobal("RoMail_Form")
	local button = form:GetText()
	local count = nil
	local index = RoMail_MailListFrame.index
	local sindex
   	local title = getglobal("RoMail_MailListFrame_TitleText")
	local srt = nil
	

	if (button=="guild") then
		count = GetNumGuildMembers()
		srt = ROMAIL_TITLE_GUILD .. " (" .. count .. ")"
	elseif (button=="friend") then
		count = GetFriendCount("Friend")
		srt = ROMAIL_TITLE_FRIEND .. " (" .. count .. ")"
	end
	
	if ROMAIL_MAX_ITEM < count then
		RoMail_MailListFrame_ScrollBar:SetMaxValue(count - 10)
		RoMail_MailListFrame_ScrollBar:Show()
	else
		RoMail_MailListFrame_ScrollBar:Hide()
	end
	
	for i=1, ROMAIL_MAX_ITEM do	
		local item = getglobal("RoMail_FLItem"..i)
		item:Hide()
	end
	
	if (button=="guild") then
		for i=1, ROMAIL_MAX_ITEM do
			sindex = index + i
			
			local name, rank, class, level, subClass, subLevel, isHeader, isCollapsed, dbid, guildTitle, IsOnLine ,LogOutTime, Zone, Note= GetGuildRosterInfo(sindex);
			local item = getglobal("RoMail_FLItem"..i)
			local Name = getglobal(item:GetName().."Name")
			
			if (IsOnLine == true) then
				Name:SetColor(0.82,0.80,0.21);
			else
				Name:SetColor(0.6,0.6,0.6);
			end
			Name:SetText(name)
			item:Show()
		end
	elseif (button=="friend") then
		for i=1, ROMAIL_MAX_ITEM do
			sindex = index + i
			
			info = {}
			
			info.name, 
			info.groupID, 
			info.online,
			info.eachOther,
			info.unmodifiable,
			info.top, 
			info.killMeCount,
			info.revengeCount,
			info.relationType,
			info.relationLv = GetFriendInfo("Friend", sindex)

			info.id = i
			
			local name = info.name
			local item = getglobal("RoMail_FLItem"..i)
			local Name = getglobal(item:GetName().."Name")
			
			if (info.online) then
				Name:SetColor(0.82,0.80,0.21);
			else
				Name:SetColor(0.6,0.6,0.6);
			end
			Name:SetText(name)
			item:Show()
		end
	end
	
	title:SetText(srt)
end

function RoMail_FriendList_OnChange(this, arg1) 
	RoMail_MailListFrame.index = RoMail_MailListFrame_ScrollBar:GetValue()
	RoMail_FriendList_Update()
end

function RoMail_FriendList_Clean_OnClick(this)
	RoMail_MailListFrame:Hide()
end

function RoMail_FriendList_OK_OnClick(this)
	RoMail_MailListFrame:Hide()
end

function RoMail_ItemOnClick(this, key)
	local index     = RoMail_MailListFrame.index
	local pern      = RoMail_MailListFrame.pern
	local id        = this:GetID()
	local item      = getglobal("RoMail_FLItem"..pern)
	local oldselect = getglobal(item:GetName().."_Select")
	oldselect:Hide()
	local select    = getglobal(this:GetName().."_Select")
	select:Show()
	local Name      = getglobal(this:GetName().."Name")
	
	SendMailNameEditBox:SetText(Name:GetText())
	RoMail_MailListFrame.pern = id
	RoMail_FriendList_Update()
end